package cn.lml.lession.auth.config;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.lml.lession.common.constant.Constant;
import cn.lml.lession.common.util.Result;

@Component("customAuthenticationEntryPoint")
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

	@Autowired
	private ObjectMapper objectMapper;
	
	public boolean isAjaxRequest(HttpServletRequest request) {
		/*String ajaxFlag = request.getHeader("X-Requested-With");
		return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);*/
		return true;
	}

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException {
		if (isAjaxRequest(request)) {
			  response.setCharacterEncoding(Constant.UTF8);
		       response.setContentType(Constant.CONTENT_TYPE);
		       response.setStatus(HttpStatus.SC_UNAUTHORIZED);
		       PrintWriter printWriter = response.getWriter();
		       printWriter.append(objectMapper.writeValueAsString(Result.error("需要授权才能访问")));
		} else {
			response.sendRedirect("/login");
		}
	}
}
